#!/bin/bash

#
# Copyright (c) 2012-2017 Codenvy, S.A.
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
#   Codenvy, S.A. - initial API and implementation
#

SRC_FOLDER=${1}
DST_FOLDER=${2}
HOST=${3}
PORT=${4}
DST_USR_ID=${5}
DST_GRP_ID=${6}
USER_NAME=${7}

##### Set by puppet #####
RSYNC_RESTORE_BWLIMIT=<%= scope.lookupvar('codenvy::rsync_restore_bwlimit') %>
SSH_LOG_LEVEL=<%= scope.lookupvar('codenvy::rsync_ssh_log_level') %>
#########################

source /opt/codenvy-data/conf/rsyncbase.sh

##### Rsync options #####
RSYNC_OPTIONS=""
RSYNC_OPTIONS+=" --quiet"
RSYNC_OPTIONS+=" --recursive"
# Throughput limit for rsync
RSYNC_OPTIONS+=" --bwlimit=${RSYNC_RESTORE_BWLIMIT}"
# Sync modification timestamps to optimise transfer of not modified files.
RSYNC_OPTIONS+=" --times"
# Delete files/folders on receiving side if they are not present on sending side.
RSYNC_OPTIONS+=" --delete"
# Preserve sym links in a safe way
RSYNC_OPTIONS+=" --links --safe-links"
# Transition of ownership and permissions
RSYNC_OPTIONS+=" --owner --group --numeric-ids --perms"
#########################

# Previously was used to overwrite permissions of root folders of syncing.
# Was left for backward compatibility and to prevent possible issues after changing behavior.
# Ensure existing trailing slash to overwrite permissions of destination folder too.
if [[ ${SRC_FOLDER} != */ ]]; then
   SRC_FOLDER=${SRC_FOLDER}"/"
fi
if [[ ${DST_FOLDER} != */ ]]; then
   DST_FOLDER=${DST_FOLDER}"/"
fi

# Include .codenvy folders and respect .gitignore files.
# Notice that not all the syntax of .gitignore is supported in rysnc (at least in v3.1.1).
# TODO consider removing of these options, looks like they are not needed/reliable
rsync ${RSYNC_OPTIONS} \
      --rsh="ssh ${SSH_OPTIONS}" \
      --rsync-path="${RSYNC_COMMAND}" \
      --include='.codenvy/' --filter=':- .gitignore' \
      ${SRC_FOLDER} ${HOST}:${DST_FOLDER}
